package com.cloud.little.test.dynamicproxy;

import com.cloud.little.test.staticproxy.Hello;
import com.cloud.little.test.staticproxy.HelloInterface;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyHandler implements InvocationHandler {

    private HelloInterface helloInterface;


    public ProxyHandler(HelloInterface helloInterface) {
        this.helloInterface = helloInterface;
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("before");
        method.invoke(helloInterface, args);
        System.out.println("after");
        return null;
    }

    public Object getProxy() {
        return Proxy.newProxyInstance(helloInterface.getClass().getClassLoader(), helloInterface.getClass().getInterfaces(), this);
    }

    public static void main(String[] args) {
        HelloInterface proxy = (HelloInterface)new ProxyHandler(new Hello()).getProxy();
        proxy.sayHello();
        proxy.sayBye();
    }
}
